/*
 * @Description: 
 * @Autor: Zhu_liangyu
 * @Date: 2020-05-09 10:52:56
 */
import router from './router'
import store from './store'
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/config/storageKey'
import { filterAsyncRouter } from '@/utils/routetool'//格式化router数据

const whiteList = ['/login'] // 路由白名单

router.beforeEach(async (to, from, next) => {
  const hasToken = Vue.ls.get(ACCESS_TOKEN);
  if (hasToken) {
    if (to.path === '/login') {
      // 如果已经登录了 则到首页
      next({ path: '/' })
    } else {
      const hasGetUserInfo = store.getters.userId
      if (hasGetUserInfo) {
        next()
      }
      else {
        try {
          //得到用户信息
          await store.dispatch('user/getInfo')

          //next()//查看用户菜单信息
          const _menus = JSON.parse(JSON.stringify(store.getters.menus));
          if (_menus.length < 1) {
            global.asyncRoutes = []
            next()
          }
          const menus = filterAsyncRouter(_menus); // 1.过滤路由

          menus.push({ path: '*', redirect: '/404', hidden: true });//3.添加全局路由拦截,路由表中不存在即转到404
          router.addRoutes(menus) // 4.添加动态路由
          global.asyncRoutes = menus // 2.将路由数据传递给全局变量，做侧边栏菜单渲染工作(这里将404隔离开来)
          next({
            ...to,
            replace: true
          }) // hack方法 确保addRoutes已完成 ,set the replace
        } catch (error) {
          // 删除token 并且跳转到登录页面
          await store.dispatch('user/resetToken')
          next(`/login?redirect=${to.path}`)
        }
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
    }
  }
})

router.afterEach(() => {

})

